<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/31
 * Time: 14:33
 */

namespace osc\mobile\controller;

use think\Db;
use think\Session;
use think\Request;

class SignIn extends MobileBase
{

    /**
     * 验证是否登录
     */
    protected function _initialize()
    {

        parent::_initialize();
        define('UID',is_login());

        if (!Session::has("username")) {

            $this->redirect('login/login');

        }

    }

    /**宝豆
     * @return mixed
     */
    public function index(){
        $username = session('username');
        if(!$username)
        {
            $this->redirect('login/login');
        }

        $start = input('param.start');
        $end = input('param.end');

        if($start && $end){
            $map = [
                "FROM_UNIXTIME(create_time,'%Y-%m-%d')" => array(['>',strtotime($start)],['<',strtotime($end)])
            ];
        }
        $map['uid'] = UID;
        $map['type'] = 1;

        $list = Db::name('release')
            ->where($map)
            ->order('create_time desc')
            ->paginate(5,false, [
                'query' => Request::instance()->param(),//不丢失已存在的url参数
            ]);

        $page=$list->render(); //获取分页

        $user_info=Db::name('member')->where(array('uid'=>UID))->find();

        $release = Db::name('release')->where(['uid'=>UID,"FROM_UNIXTIME(create_time,'%Y-%m-%d')"=>date('Y-m-d',time()),'type'=>1])->find();

        $this->assign('user_info',$user_info);
        $this->assign('release',$release);
        $this->assign('start',$start);
        $this->assign('end',$end);
        $this->assign('list',$list);
        $this->assign('page',$page);
        $this->assign('empty',"<span style='margin-left:20px;'>没有数据</span>");

        $this->assign('top_title','我的通分');
        $this->assign('SEO',['title'=>'我的通分-'.config('SITE_TITLE')]);

        return $this->fetch();
    }

    /**
     * 宝豆签到释放处理
     * @return array
     */
    public function sign_in()
    {
        if($this->request->isAjax())
        {
            $data = $this->request->param();
            $username = session('username');
            //查询是否重复提交
            $token = Db::name('token')->where('token',$data['token'])->find();

            if($token){
                return ['error'=>'请勿重复提交'];
            }

            //查询当天是否申请过
            $release = Db::name('release')->where(['username'=>$username,"FROM_UNIXTIME(create_time,'%Y-%m-%d')"=>date('Y-m-d',time()),'type'=>1])->find();
            if($release){
                return ['error'=>'抱歉，您当天已申请过'];
            }

            //查询用户信息
            $user = Db::name('member')->where('username',$username)->find();

            if($user['score'] < 0 || $user['score'] == 0){
                return ['error'=>'抱歉，您的余额不足'];
            }

            //获取释放利率后的金额
            $release = get_release_rate($user['score']);

//            print_r($release);exit;
            //设置释放记录
            $map = [
                'username'      => $username,
                'uid'           => UID,
                'rate'          => $release['rate'],
                'num'           => $release['num'],
                'type'          => 1,
                'create_time'   => time()
            ];

            // 开启事务
            Db::startTrans();
            try{
                //扣除宝豆增加吉豆录入释放记录
                Db::name('member')->where('username',$username)
                    ->inc('card',$map['num']*0.7)
                    ->inc('integrals',$map['num']*0.2)
                    ->inc('welfare',$map['num']*0.1)
                    ->update();
                Db::name('member')->where('username',$username)->setDec('score',$map['num']);

                Db::name('release')->insert($map);

                Db::name('token')->insert(['token'=>$data['token']]);

                // 更新成功 提交事务
                Db::commit();

                return ['success'=>'签到成功'];

            }catch (\Exception $e){
                // 更新失败 回滚事务
                Db::rollback();

                return ['error'=>'签到失败'];
            }
        }
    }



    /**
     * 用户元宝转让
     * @return array|mixed
     */
    public function jilin_turn()
    {
        $user = session('username');

        if(request()->isPost()){

            $data=input('post.');
            $data['token']  = input('post.__token__/s', null);

            if(is_int($data['num']))
            {
                return array('error'=>'转让数量必须输入整数!');
            }

            if($data['num'] <= 0)
            {
                return array('error'=>'转让金额必须大于0!');
            }

            if($data['num']%10  != 0 ){
                return array('error'=>'请输入10的整数倍!');
            }

            return $r=osc_service('common','Member')->jilin_usertf($data);

        }

        $list = Db::name('jilin_usertf')->where("username = $user or mobile = $user")->order('dt desc')->limit(50)->select();

        $this->assign('list',$list);
        $this->assign('user',$user);
        $this->assign('top_title','元宝转让');
        $this->assign('SEO',array('title'=>'元宝转让-'.config('SITE_TITLE')));
        return $this->fetch();

    }

    /**
     * 获取用户真实姓名
     * @return array
     */
    function getUserinfo()
    {
        if(request()->isPost()){

            $data=input('post.');

            if($data['mobile'])
            {
                $ret = Db::name('member')->where('username',$data['mobile'])->find();

                $dt['nickname'] = $ret['nickname'];
                $dt['username'] = $ret['username'];
                $dt['idcardname'] = $ret['idcardname'];

                return array($dt['idcardname']);

            }

        }
    }

}